package com.liarjo.my_website_api.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.liarjo.my_website_api.util.JwtUtil;
import com.liarjo.my_website_api.util.JwtUtil.JwtStatus;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;


public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // 从请求头中获取 Token
        String token_raw = request.getHeader("Authorization");

        // 如果 Token 不存在，返回 401 未授权
        if (token_raw == null || !token_raw.startsWith("Bearer ")) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        String token = token_raw.replaceFirst("^Bearer ", "").trim();
        JwtStatus tokenStatus = jwtUtil.validateToken(token);
        request.setAttribute(AppConstants.TOKEN, token);

        if (tokenStatus == JwtStatus.TOKEN_VALID) {
            // 刷新token
            if (jwtUtil.isTokenExpiringSoon(token)) {
                String newToken = jwtUtil.refreshToken(token);
                response.setHeader("X-New-Token", newToken);
            }
            // 没问题,就返回true
            return true;
        } else {
            // Token 无效或过期
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setHeader(AppConstants.ERROR, tokenStatus.name());
            return false;
        }
    }
}
